package cn.bearspark.gateway.config;

import cn.bearspark.gateway.handler.NoTokenExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

/**
 * 异常处理器的配置类
 *
 * @author f
 */
@Configuration(proxyBeanMethods = false)
public class ExceptionHandlerConfig {

    private final ServerProperties serverProperties;

    public ExceptionHandlerConfig(ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    /**
     * 配置没有 token 的异常处理器
     */
    @Bean
    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes,
                                                             WebProperties webProperties,
                                                             ObjectProvider<ViewResolver> viewResolvers,
                                                             ServerCodecConfigurer serverCodecConfigurer,
                                                             ApplicationContext applicationContext) {
        NoTokenExceptionHandler noTokenExceptionHandler = new NoTokenExceptionHandler(
                errorAttributes,
                webProperties.getResources(),
                serverProperties.getError(),
                applicationContext
        );
        noTokenExceptionHandler.setViewResolvers(viewResolvers.stream().toList());
        noTokenExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
        noTokenExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
        return noTokenExceptionHandler;
    }

}
